package api

import (
	"gitee.com/kristas/booting-go/framework"
	"gitee.com/kristas/booting-go/framework/common/util/snowflake"
	"gitee.com/kristas/booting-go/framework/core/log"
	"gitee.com/kristas/booting-go/framework/core/statement/types"
	. "gitee.com/kristas/booting-go/plugin/websocket_plugin"
	"github.com/gorilla/websocket"
	"strconv"
)

func init() {
	framework.Component(new(WsHandler))
}

type WsHandler struct {
	types.Websocket `endpoint:"/ws/channel/v1"`
	Log             log.Logger `wire:""`
}

func (w *WsHandler) OnOpen(session *Session) {
	worker, _ := snowflake.NewWorker(1)
	id := strconv.Itoa(int(worker.GetId()))
	session.Set("id", id)
	w.Log.Info("websocket[%s][connected]", id)
}

func (w *WsHandler) OnClose(session *Session) {
	id, _ := session.Get("id")
	w.Log.Info("websocket[%s][closed]", id)
}

func (w *WsHandler) OnMessage(session *Session, message []byte) error {
	id, _ := session.Get("id")
	w.Log.Info("websocket[%s][message]: %s", id, message)
	go func() {
		<-session.Context.Done()
		w.Log.Info("done")
	}()
	return session.WriteMessage(websocket.TextMessage, message)
}

func (w *WsHandler) OnError(session *Session, err error) {
	id, _ := session.Get("id")
	w.Log.Error("websocket[%s][error]: %s", id, err)
}
